package com.bms.admin.base.user.web;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bms.admin.base.index.model.NowUser;
import com.bms.admin.base.user.entity.User;
import com.bms.admin.base.user.service.IUserService;
import com.bms.admin.config.annotation.LoginUser;
import com.bms.auth.annotation.RequiresPermissions;
import com.bms.common.base.common.bean.Result;
import com.bms.common.base.common.exception.EnumSvrResult;
import com.bms.common.base.common.util.MD5Util;
import com.bms.common.base.web.BaseController;
import com.feilong.core.Alphabet;
import com.feilong.core.Validator;
import com.feilong.core.util.RandomUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * <p>
 * 系统用户  前端控制器
 * </p>
 *
 * @author xj
 * @since 2018-08-09
 */
@RestController
@RequestMapping("/user")
@Api(value="User-Api",tags="用户管理")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;

	@ApiOperation("获取用户列表")
	@GetMapping("/list")
	@RequiresPermissions("user:list")
    public Result list(@RequestParam(defaultValue = "1",required=false)Integer pageNum,
    				   @RequestParam(defaultValue = "20",required=false)Integer pageSize,
    				   @ApiIgnore @LoginUser NowUser nowUser,
    				   String username) {
		Wrapper<User> ew = new EntityWrapper<User>();
		ew.isWhere(true).like(Validator.isNotNullOrEmpty(username),"username", username);
		if (nowUser.getUserId()!=1) {
			ew.eq("company_id", nowUser.getCompanyId());
		}
		ew.orderBy("create_time", false);
		return json(userService.queryByPage(new Page<User>(pageNum,pageSize),ew));
    }

	/**
	 * 验证用户名是否存在
	 * @param username
	 * @return
	 */
	@GetMapping("/exists/{username}")
	public Result exists (@PathVariable String username) {

		EntityWrapper<User> ew = new EntityWrapper<>();
		ew.eq("username", username);
		User user = userService.selectOne(ew);

		if (null == user) {
			return success();
		}

		return error();
	}

	@ApiOperation("获取用户信息")
	@GetMapping("/info/{userId}")
	@RequiresPermissions("user:info")
    public Result select(@PathVariable Long userId){
		return json(userService.queryById(userId));
    }

	/**
	 * 启用禁用
	 * @param userId
	 * @param status
	 * @return
	 */
	@ApiOperation("状态修改")
	@PostMapping("/enable")
	@RequiresPermissions("user:enable")
	public Result enable (@ApiIgnore @LoginUser NowUser nowUser, @RequestParam Long userId, @RequestParam Integer status) {

		User user = userService.selectById(userId);

		if (null == user) {
			return fail(EnumSvrResult.DEFIN_ACCOUNT);
		}

		if (userId == 1) {
			return fail(EnumSvrResult.ERROR_DELETE_ADMIN);
		}

		user.setStatus(status);
		user.setUpdateUser(nowUser.getUsername());
		user.setUpdateTime(new Date(System.currentTimeMillis()));
		userService.updateAllColumnById(user);

		return success();
	}

	@ApiOperation("新增后台用户")
	@PostMapping("/save")
	@RequiresPermissions("user:save")
	public Result save(@ApiIgnore @LoginUser NowUser nowUser,@Validated @RequestBody User user){
		Date now = new Date();
		user.setCreateTime(now);
		user.setCreateUser(nowUser.getUsername());
		user.setStatus(1);
		user.setUpdateTime(now);
		String salt = RandomUtil.createRandomFromString(Alphabet.DECIMAL_AND_LOWERCASE_LETTERS_DISTINGUISHABLE, 20);
		user.setPassword(MD5Util.inputPassToDbPass(user.getPassword(), salt));
		user.setSalt(salt);
		userService.insert(user);
		return success();
	}

	@ApiOperation("修改用户信息")
	@PostMapping("/update")
	@RequiresPermissions("user:update")
	public Result update(@ApiIgnore @LoginUser NowUser nowUser,@RequestBody User user){
		user.setUpdateTime(new Date());
		user.setUpdateUser(nowUser.getUsername());
		userService.updateById(user);
		return success();
	}

	@ApiOperation("删除用户")
	@DeleteMapping("/delete")
	@RequiresPermissions("user:delete")
    public Result delete(@ApiIgnore @LoginUser NowUser nowUser,@RequestBody List<Long> userIds) {
		if(userIds.contains(1L)) {
			return fail(EnumSvrResult.ERROR_DELETE_ADMIN);
		}
		if(userIds.contains(nowUser.getUserId())) {
			return fail(EnumSvrResult.ERROR_DELETE_ONLINE);
		}
		userService.deleteByIds(userIds);
		return success();
    }


	@ApiOperation("锁屏解锁")
	@PostMapping("/unlock")
    public Result unlock(@ApiIgnore @LoginUser NowUser nowUser,@RequestParam String password) {
		User user = userService.selectById(nowUser.getUserId());
	    if(user.getStatus()!=1){
	        return fail(EnumSvrResult.LOCKED_ACCOUNT);
	    }else if(!MD5Util.inputPassToDbPass(password, user.getSalt()).equals(user.getPassword())){
	        return fail(EnumSvrResult.ERROR_PASSWORD);
	    }
		return success();
    }

	@ApiOperation("更换头像")
	@PostMapping("/changeAvatar")
	public Result changeAvatar(@ApiIgnore @LoginUser NowUser nowUser,@RequestParam String headImg) {
		User user = userService.selectById(nowUser.getUserId());
		user.setHeadImg(headImg);
		userService.updateById(user);
		return success();
	}


	@ApiOperation("密码修改")
	@PostMapping("/modifyPassword")
	public Result modifyPassword (@RequestParam Long id, @RequestParam String oldPass, @RequestParam String newPass) {

		Result res = new Result();

		User user = userService.queryById(id);

		if (null != user) {
			if (!user.getPassword().equals(MD5Util.inputPassToDbPass(oldPass, user.getSalt()))) {
				res.setMessage("原密码错误");
				res.setStatus(EnumSvrResult.ERROR_MSG_CODE.getVal());
				return res;
			}
			user.setPassword(MD5Util.inputPassToDbPass(newPass, user.getSalt()));
			user.setUpdateTime(new Date(System.currentTimeMillis()));
		}

		userService.updateById(user);

		return res;
	}
}
